package com.example.dicos.service.impl;

import com.example.dicos.entity.WxRolePermissionRelation;
import com.example.dicos.entity.dot.WxRolePermissionRelationDto;
import com.example.dicos.entity.vo.WxPermissionVo;
import com.example.dicos.mapper.WxRolePermissionRelationMapper;
import com.example.dicos.service.WxRolePermissionRelationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 后台用户角色和权限关系表 服务实现类
 * </p>
 *
 * @author 开发者
 * @since 2022-07-11
 */
@Service
public class WxRolePermissionRelationServiceImpl implements WxRolePermissionRelationService {
    @Autowired
    private WxRolePermissionRelationMapper wxRolePermissionRelationMapper;

    /**
     * 角色分配权限
     *
     * @param wxRolePermissionRelationDto
     * @return
     */
    @Override
    public Integer addWxRolePermissionRelation(WxRolePermissionRelationDto wxRolePermissionRelationDto) throws Exception {
        WxRolePermissionRelation wxRolePermissionRelation = new WxRolePermissionRelation();
        String[] permissionId = wxRolePermissionRelationDto.getPermissionId();
        if (permissionId.length == 0) {
            throw new Exception("分配权限不能为空");
        }
        List<WxRolePermissionRelation> wxPermissionVos = wxRolePermissionRelationMapper.queryWxPermissionVoById(wxRolePermissionRelationDto.getRoleId());
        if (wxPermissionVos.size() > 0) {
            wxPermissionVos.stream().forEach(del -> {
                wxRolePermissionRelationMapper.deleteById(del.getRoleId());
            });
        }
        List<String> strings = Arrays.asList(permissionId);
        BeanUtils.copyProperties(wxRolePermissionRelationDto, wxRolePermissionRelation);
        strings.stream().forEach(s -> {
            wxRolePermissionRelation.setPermissionId(s);
            wxRolePermissionRelationMapper.insert(wxRolePermissionRelation);
        });
        return 1;
    }


    @Override
    public List<WxPermissionVo> queryWxPermissionVoList(Long roleId) {
        return wxRolePermissionRelationMapper.queryWxPermissionVoList(roleId);
    }
}
